package com.example.demo.producer_consumer;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 参考：https://cloud.tencent.com/developer/article/1837462
 */
public class MyBlockingQueue {

    private Integer limit = 10;

    private Queue queue = new LinkedList();

    public MyBlockingQueue(Integer limit) {
        this.limit = limit;
    }

    public synchronized boolean push(Object o) throws InterruptedException {
        //如果队列满了，就等待
        while (this.queue.size() == this.limit){
            wait();
        }
        // 如果队列为空了，就唤醒所有阻塞的线程。
        if(this.queue.size() == 0){
            notifyAll();
        }
        boolean add = this.queue.offer(o);
        return add;
    }

    public synchronized Object pop() throws InterruptedException {
        while(this.queue.size() == 0){
            wait();
        }
        // 如果队列重新满了之后，唤醒阻塞的所有线程。
        if (this.queue.size() == this.limit){
            notifyAll();
        }
        Object poll = this.queue.poll();
        return poll;
    }

    public static void main(String[] args) {
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(10);
        LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue();
    }

}
